﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chowpoo.Common;
using Chowpoo.Util;
using CourseSystem.Common;
using CourseSystem.Common.Helpers;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;
using CourseSystem.Core.Enum;
using CourseSystem.Stat.ActionFilter;
using Webdiyer.WebControls.Mvc;
namespace CourseSystem.Web.Controllers
{
    [UserAuth(UserType = UserTypeEnum.Student)]
    public class ExamLibController : BaseController
    {
        public ActionResult Index(byte? type)
        {
            type = type.CheckByte(0);
            ViewData["type"] = type;
            switch (type)
            {
                case 0:
                    return RedirectToAction("Homework", new { type = 1 });
                case 1:
                    return RedirectToAction("Homework", new { type = 0 });
                case 2:
                    return RedirectToAction("Exam");
                case 3:
                    return RedirectToAction("Excellent");
                case 4:
                    return RedirectToAction("Score", new { type = 0 });
            }
            return NotFound();
        }

        [StatFilter]
        [UrlStatFilter]
        [UserAuth(IsLimt = true, UserType = UserTypeEnum.Student)]
        public ActionResult Score(int? type)
        {
            type = type.CheckInt(0);
            ViewData["type"] = type;
            return View();
        }
        [StatFilter]
        [UrlStatFilter]
        public ActionResult Excellent()
        {
            return View();
        }

        public ActionResult ExcellentListUc(int? pid)
        {
            CommonRequest.ClearCache();
            var list = ExamSummaryBLL.GetList(1, "", "", -1, 1).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }
        [StatFilter]
        [UrlStatFilter]
        public ActionResult Homework(int? id, int? type)
        {
            type = type.CheckInt(0);
            var info = SectionBLL.Get(id);
            if (info == null)
                return NotFound();
            var examInfo = ExaminationBLL.GetList(type.Value, info.Id).FirstOrDefault();
            if (examInfo == null)
            {
                SetErrorMsg("未设置相关试题.");
                return NotFound();
            }
            return View(examInfo);

        }
        /*[StatFilter]
        [UrlStatFilter]
        public ActionResult Exercise()
        {
            return View();
        }*/

        public ActionResult ExerciseListUc(int? pid)
        {
            CommonRequest.ClearCache();
            // var list = ExaminationBLL.GetList(1, true).OrderByDescending(o => o.Id);
            //  var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            //return PartialView(model);
            return null;
        }

        public ActionResult ScoreListUc(int? pid, int type)
        {
            CommonRequest.ClearCache();
            var list = ExamSummaryBLL.GetList(UserHelper.LoginUser.Id, type).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult ExamListUc(int? pid)
        {
            CommonRequest.ClearCache();
            var list = ExaminationBLL.GetExamList(UserHelper.Student.ClassId, UserHelper.Student.GradeYear);
            //排除补考试卷
            var listList = list.ToList();
            var commonItem =
                listList.FirstOrDefault(
                    o =>
                    !o.Title.Contains("补考") && o.ExamSummaryInfo.FirstOrDefault() != null &&o.ExamSummaryInfo.FirstOrDefault().IsCommit&&
                    o.ExamSummaryInfo.FirstOrDefault().Score < 60);

            if (commonItem == null)
            {
                commonItem =
                    listList.FirstOrDefault(
                        o =>
                        !o.Title.Contains("补考"));
                if (commonItem == null || commonItem.StartTime.AddMinutes(30) > DateTime.Now)
                {
                    listList.RemoveAll(o => o.Title.Contains("补考"));
                    list = listList.AsQueryable();
                }
            }
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        [UserAuth(IsLimt = true, UserType = UserTypeEnum.Student)]
        [StatFilter]
        [UrlStatFilter]
        public ActionResult Exam()
        {
            return View();
        }

        [UserAuth(IsLimt = true, UserType = UserTypeEnum.Student)]
        [StatFilter]
        //[UrlStatFilter]
        public ActionResult ExamDetail(int id, int? reExam)
        {
            reExam = reExam.CheckInt(0);
            ViewData["reExam"] = reExam;
            var info = ExaminationBLL.Get(id);
            if (info == null)
            {
                return NotFound();
            }
            ViewData["reExam"] = info.Title.Contains("补考") ? 1 : 0;
            ViewData.Model = info;
            if (info.Type != 4)
            {

                return NotFound();
            }

            if (!ExamLibHelper.IsCanExam())
            {
                SetAlertMsg("学习进度大于70%才能进行考试!", true);
                return RedirectToAction("Exam");
            }

            if (UserHelper.Student.ClassId != info.ClassId || UserHelper.Student.GradeYear != info.YearId)
            {
                SetAlertMsg("你不是该专业该年级的学生!不能参加该考试!", true);
                return RedirectToAction("Exam");
            }

            var sumInfo =
          info.ExamSummaryInfo.FirstOrDefault(
              o => o.Uid == UserHelper.LoginUser.Id && o.Eid == id);
            if (sumInfo != null && sumInfo.IsCommit)
            {
                if (reExam == 0)
                    SetAlertMsg("已成功提交该考试!", true);
                else
                    SetAlertMsg("补考完成!", true);
                return RedirectToAction("Exam");
            }
            var statusInfo = ExamStatusBLL.Get(id, UserHelper.LoginUser.Id);

            var now = DateTime.Now;

            if (sumInfo == null && reExam == 0)
            {
                if (now > info.StartTime.AddMinutes(30))
                {
                    if (info.Title.Contains("补考"))
                        SetAlertMsg("补考开始半小时后禁止进入考试,你已经没有机会考试!", true);
                    else
                        SetAlertMsg("考试开始半小时后禁止进入考试,请等待进行补考!", true);
                    return RedirectToAction("Exam");
                }
            }
            if (reExam == 1 || (info.StartTime <= now && info.EndTime >= now))
            {

            }
            else
            {
                SetAlertMsg("该考试尚未开始或已结束!", true);
                return RedirectToAction("Exam");
            }


            if (statusInfo == null)
            {
                if (!ExamStatusBLL.Add(new ExamStatusInfo
                                      {
                                          Eid = id,
                                          IsWarning = false,
                                          StudentId = UserHelper.LoginUser.Id,
                                          Status = 0
                                      }))
                {
                    SetErrorMsg("添加统计信息失败!");
                    return NotFound();
                }
                return View();
            }
            if (statusInfo.Status == 1)
            {
                SetAlertMsg("您已提交该考试!不能修改!", true);
                return RedirectToAction("Exam");
            }
            if (statusInfo.Status == 1)
            {
                statusInfo.Status = 0;
                statusInfo.StartTime = now;
                if (!ExamStatusBLL.Edit(statusInfo))
                {
                    SetErrorMsg("未知错误");
                    return NotFound();
                }
            }
            return View();
        }

        public ActionResult ChapterTreeUc(int id, int type)
        {
            if (id != 0)
            {
                var info = SectionBLL.Get(id);
                if (info == null)
                    return NotFound();
                ViewData["curr"] = info;
            }
            else
            {
                ViewData["curr"] = SectionBLL.Get(null); 
            }
            var chapterList = ChapterBLL.GetList().OrderBy(o => o.OrderId);
            ViewData.Model = chapterList;
            ViewData["type"] = type;
            return PartialView();
        }

        [UserAuth(IsLimt = true, UserType = UserTypeEnum.Student)]
        [HttpPost]
        public ActionResult ExamSave(int id)
        {
            var info = ExaminationBLL.Get(id);
            if (info == null)
            {
                SetErrorMsg("Id错误.该试卷可能已被删除.");
                return NotFound();
            }
            var statusInfo = info.ExamStatusInfo.FirstOrDefault(o => o.StudentId == UserHelper.Student.Id);
            if (info.Type == 4 && statusInfo == null)
            {
                SetErrorMsg("统计信息为空.无法提交.");
                return NotFound();
            }

            if (info.Type == 4 && info.Status != 1)
            {
                SetAlertMsg("该试卷未发布!不能提交!", true);
                return RedirectToAction("Index");
            }
            //安全性检查,已提交的作业不能更改
            var sumInfo = info.ExamSummaryInfo.FirstOrDefault(o => o.Uid == UserHelper.LoginUser.Id);
            //补考
            var reExam = info.Type == 4 && info.Title.Contains("补考"); //&& statusInfo != null && statusInfo.StartTime > info.StartTime.AddMinutes(30);
            /*&& (sumInfo != null && sumInfo.IsCommit && sumInfo.Score < 60 && statusInfo.CommitTimes == 1 ||
            ((sumInfo == null || !sumInfo.IsCommit&&statusInfo.StartTime>info.StartTime.AddMinutes(30)) && info.StartTime.AddMinutes(30) < DateTime.Now));*/
            if (info.Type == 4)
            {
                if (UserHelper.Student.ClassId != info.ClassId || UserHelper.Student.GradeYear != info.YearId)
                {
                    SetAlertMsg("你不是该专业该年级学生!不能提交该考试!", true);
                    return RedirectToAction("Exam");
                }
                var now = DateTime.Now;
                if (info.StartTime <= now && info.EndTime.AddMinutes(1) >= now)
                {

                }
                else
                {
                    SetAlertMsg("该试卷尚未开始或已结束!无法提交!", true);
                    return RedirectToAction("Exam");
                }
            }

            if (sumInfo != null && sumInfo.IsCommit)
            {
                SetAlertMsg("不能重复提交!", true);
                goto End;
            }
            var answerList = new List<ExamAnswerInfo>();
            var canSumScore = true;
            foreach (var item in info.ExaminationItemInfo)
            {
                var addInfo = new ExamAnswerInfo
                                  {
                                      Uid = UserHelper.LoginUser.Id,
                                      Eid = id,
                                      Qid = item.QuestionLibInfo.Id
                                  };
                switch (item.QuestionLibInfo.Type)
                {
                    //单选
                    case 0:
                        var key = Request["radio" + item.QuestionLibInfo.Id].CheckInt(0);
                        var qKey = item.QuestionLibInfo.RadioChoicesInfo.FirstOrDefault(o => o.IsAnswer);
                        addInfo.AnswerId = key;
                        addInfo.Score = (qKey != null && key == qKey.Id) ? ExamLibHelper.GetScoreTran(item.QuestionLibInfo.Score, info.Score) : 0;
                        break;
                    //多选
                    case 1:
                        var key1 = item.QuestionLibInfo.RadioChoicesInfo.Where(itemCheck => string.Equals(Request["check" + itemCheck.Id], "true,false")).Aggregate(",", (current, itemCheck) => current + itemCheck.Id + ",");
                        var qKey1 = item.QuestionLibInfo.RadioChoicesInfo.Where(o => o.IsAnswer).ToList();
                        var key1Array = key1.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        var score = 0;
                        if (qKey1.Count != 0 && qKey1.Count == key1Array.Length)
                        {
                            score = ExamLibHelper.GetScoreTran(item.QuestionLibInfo.Score, info.Score);
                            if (qKey1.Any(keyItem => !key1.Contains("," + keyItem.Id + ",")))
                            {
                                score = 0;
                            }
                        }
                        addInfo.Answer = key1;
                        addInfo.Score = score;
                        break;
                    //判断题
                    case 2:
                        var key2 = Request["checkpan" + item.QuestionLibInfo.Id] == "true,false" ? "" : "1";
                        addInfo.Answer = key2;
                        var qkey2 = string.IsNullOrEmpty(item.QuestionLibInfo.QuestionAnswerInfo.Answer);
                        addInfo.Score = string.IsNullOrEmpty(key2) == qkey2
                                            ? ExamLibHelper.GetScoreTran(item.QuestionLibInfo.Score, info.Score)
                                            : 0;
                        break;
                    //论述题
                    case 3:
                        var key3 = Request["area" + item.QuestionLibInfo.Id].CheckStr("");
                        addInfo.Answer = key3;
                        canSumScore = false;
                        break;
                    //思考题
                    case 4:
                        var key4 = Request["area" + item.QuestionLibInfo.Id].CheckStr("");
                        addInfo.Answer = key4;
                        canSumScore = false;
                        break;
                }
                answerList.Add(addInfo);
            }

            if (answerList.Count < 1)
                goto End;

            if (ExamAnswerBLL.EditList(id, UserHelper.LoginUser.Id, answerList))
            {
                var reMsg = "保存成功.";
                var sumScore = answerList.Sum(o => o.Score);
                if (sumInfo == null)
                {
                    var addSumInfo = new ExaminationSummaryInfo { Eid = id, Uid = UserHelper.LoginUser.Id, IsScoring = canSumScore, Score = sumScore };
                    if (info.Type == 4 && Request["Submit"] != null)
                    {
                        if (reExam)
                        {
                            if (addSumInfo.Score > 60)
                                addSumInfo.Score = 60;
                        }
                        if (info.Type == 4 && statusInfo != null && statusInfo.StartTime.AddMinutes(30) > DateTime.Now)
                        {
                            SetAlertMsg("考试开始30分钟内不能提交!", true);
                            goto End;
                        }
                        addSumInfo.IsCommit = true;
                        reMsg = "提交成功.";
                        if (statusInfo != null)
                        {
                            statusInfo.Status = 1;
                            ExamStatusBLL.Edit(statusInfo);
                        }
                    }

                    if (ExamSummaryBLL.Add(addSumInfo))
                    {
                        if ((info.Type == 0 || info.Type == 2) && Request["Submit"] != null)
                        {
                            reMsg = "提交成功,请查看答题情况.";
                            SetAlertMsg(reMsg, true);
                            return RedirectToAction("HomeworkKey", new { id });
                        }
                        SetAlertMsg(reMsg, true);
                        goto End;
                    }
                    SetAlertMsg("未知错误", true);
                    goto End;
                }
                sumInfo.IsScoring = canSumScore;
                if (!reExam)
                    sumInfo.Score = sumScore;
                if (info.Type == 4 && Request["Submit"] != null)
                {
                    if (info.Type == 4 && statusInfo != null && statusInfo.StartTime.AddMinutes(30) > DateTime.Now)
                    {
                        SetAlertMsg("考试开始30分钟内不能提交!", true);
                        goto End;
                    }
                    sumInfo.Score = sumScore;
                    if (reExam)
                    {
                        if (sumInfo.Score > 60)
                            sumInfo.Score = 60;
                    }
                    sumInfo.IsCommit = true;
                    reMsg = "提交成功.";
                    if (statusInfo != null)
                    {
                        statusInfo.Status = 1;
                        if (reExam)
                            statusInfo.CommitTimes = 2;
                        ExamStatusBLL.Edit(statusInfo);
                    }
                }

                if (ExamSummaryBLL.Edit(sumInfo))
                {
                    if ((info.Type == 0 || info.Type == 2) && Request["Submit"] != null)
                    {
                        reMsg = "提交成功,请查看答题情况.";
                        SetAlertMsg(reMsg, true);
                        return RedirectToAction("HomeworkKey", new { id });
                    }
                    SetAlertMsg(reMsg, true);
                    goto End;
                }
                SetAlertMsg("未知错误", true);
                goto End;
            }

        End:
            switch (info.Type)
            {
                case 0:
                case 1:
                case 2:
                case 3:
                    return RedirectToAction("Homework", new { id = info.SectionId, type = info.Type }); break;
                case 4:
                    return RedirectToAction("ExamDetail", new { info.Id, reExam = reExam ? 1 : 0 }); break;
            }
            SetErrorMsg("未知错误.");
            return NotFound();
        }

        [StatFilter]
        public ActionResult HomeworkKey(int id)
        {
            var info = ExaminationBLL.Get(id);
            if (info == null)
            {
                return NotFound();
            }
            if (info.Type != 0 && info.Type != 2)
                return NotFound();
            var sumInfo = info.ExamSummaryInfo.FirstOrDefault(o => o.Uid == UserHelper.Student.Id);
            ViewData.Model = sumInfo;
            return View();
        }

        [StatFilter]
        public ActionResult ExcellentDetail(int id)
        {
            var info = ExamSummaryBLL.Get(id);
            if (info == null)
            {
                return NotFound();
            }
            if (info.ExaminationInfo.Type != 1 || !info.IsExcellent)
                return NotFound();
            ViewData.Model = info;
            return View();
        }

    }
}
